#include <bits/stdc++.h>
#define ll long long 
using namespace std;

const int Maxn=1010;
int T;
int mod,n;

mt19937 rnd(147744151);
struct Matrix{
    int a[Maxn][Maxn];
    inline void clear(){memset(a,0,sizeof a);}
    inline void init(){for(int i=1;i<=n;i++) a[i][i]=1;}
    Matrix(){clear();}
}A,B,C;

inline Matrix operator *(const Matrix x,const Matrix y){
    Matrix z;
    for(int i=1;i<=1;i++)
        for(int j=1;j<=n;j++)
            for(int k=1;k<=n;k++)
                z.a[i][j]=(z.a[i][j]+1ll*x.a[i][k]*y.a[k][j]%mod)%mod;
    return z;   
}

int main(){
	freopen("matrix.in","r",stdin);
	freopen("matrix.out","w",stdout);
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&mod,&n);
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&A.a[i][j]);
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&B.a[i][j]);
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&C.a[i][j]);
        Matrix Z;

        bool tag=1;
        for(int t=1;t<=5;t++){
            for(int i=1;i<=n;i++) Z.a[1][i]=rnd()%mod;
            Matrix n1=Z*A*B,n2=Z*C;
            for(int i=1;i<=n;i++) if(n1.a[1][i]!=n2.a[1][i]) tag=0;
        }
        if(tag) puts("Yes");
        else puts("No");
    }
    return 0;
}
/*
3
5
3
0 3 1
1 1 4
3 4 4
0 4 2
1 4 3
3 0 0
1 2 4
3 3 0
1 3 3
5
3
1 0 4
2 0 0
0 2 2
3 0 4
0 4 0
4 3 2
4 2 2
1 0 3
3 4 4
6
3
1 2 5
0 3 5
5 3 4
0 0 5
2 4 5
4 4 3
0 4 2
2 2 0
4 4 4
*/
